package org.cid54.bukkit.command;

import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.event.player.PlayerChatEvent;
import org.cid54.bukkit.Cid54PlayerListener;
import org.cid54.bukkit.command.util.PlayerCommand;

/**
 *
 * @author Cid54
 */
public class SphereCommand implements PlayerCommand {

    private void setBlock(World w, Location oriLoc, int x, int y, int z, Material mat) {

        Location l = Cid54PlayerListener.cloneLocation(oriLoc);

        l.setX(l.getX() + x);
        l.setY(l.getY() + y);
        l.setZ(l.getZ() + z);

        w.getBlockAt(l).setType(mat);

    }

    @Override
    public boolean execute(String command, PlayerChatEvent event, Cid54PlayerListener listener) {

        String[] commands = command.split(" ");

        if (commands.length > 1) {

            int r = Integer.parseInt(commands[1]);

            Material mat = Material.getMaterial(Integer.parseInt(commands[2]));

            Location loc = Cid54PlayerListener.cloneLocation(event.getPlayer().getLocation());

            World w = event.getPlayer().getWorld();

            //y² + x² + z² = r²

            for (int y = -r; y <= r; y++) {

                for (int x = -r; x <= r; x++) {

                    double z = Math.sqrt(r * r - x * x - y * y);

                    if (!Double.isNaN(z) && !Double.isInfinite(z)) {

                        setBlock(w, loc, x, y, (int) z, mat);
                        setBlock(w, loc, x, y, (int) -z, mat);

                        setBlock(w, loc, (int) z, y, x, mat);
                        setBlock(w, loc, (int) -z, y, x, mat);

                        setBlock(w, loc, x, (int) z, y, mat);
                        setBlock(w, loc, x, (int) -z, y, mat);

                    }
                }

            }

            return true;
        }
        return false;

    }

    @Override
    public String getCommand() {
        return "sphere";
    }

    @Override
    public String getHelpText() {
        return "Sphere <radius> <material_id>. Creates a sphere around you.";
    }
}
